package google.architecture.common.base;

import android.content.Context;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

import google.architecture.coremodel.rx.RxBus;
import google.architecture.coremodel.rx.RxEvent;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

/**
 * <p>Activity基类 </p>
 *
 * @name BaseActivity
 */
public abstract class BaseActivity extends AppCompatActivity {

    protected String TAG = this.getClass().getName();

    protected RxBus mRxBus;
    private MyCountDownTimer mCountDownTimer;
    protected static int mCountDown = 2 * 60;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ViewManager.getInstance().addActivity(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        //是否启动倒计时，默认不启动，可以重写此方法,来启动倒计时
        startCountDown();
    }


    private void startCountDown() {
        if (isStartCountDown()) {
            if (mCountDownTimer == null)
                mCountDownTimer = new MyCountDownTimer(mCountDown * 1000, 1000);
            mCountDownTimer.start();
        }
    }

    private void stopCountDown() {
        if (isStartCountDown() && mCountDownTimer != null)
            mCountDownTimer.cancel();
    }

    @Override
    protected void onPause() {
        super.onPause();
        stopCountDown();
    }

    protected void initRxBus() {
        mRxBus = RxBus.getIntanceBus();
        registerRxBus(RxEvent.class, mConsumer);
    }

    protected void unSubscribeRxBus() {
        if (mRxBus != null)
            mRxBus.unSubscribe(this);
    }

    public <T> void registerRxBus(Class<T> eventType, Consumer<T> action) {
        Disposable disposable = mRxBus.doSubscribe(eventType, action, new Consumer<Throwable>() {
            @Override
            public void accept(@NonNull Throwable throwable) throws Exception {
                Log.e(TAG, "registerRxBus------>throwable:" + throwable.toString());
            }
        });
        mRxBus.addSubscription(this, disposable);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_UP) {
            startCountDown();
        } else if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            stopCountDown();
            View v = getCurrentFocus();
            boolean isShouldHideInput = isShouldHideInput(v, ev);
            if (isShouldHideInput) {
                v.clearFocus();
                if (hideInputMethod(this, v)) {
//                    return true; //隐藏键盘时，其他控件不响应点击事件==》注释则不拦截点击事件
                }
            }
        } else {
            stopCountDown();
        }
        return super.dispatchTouchEvent(ev);
    }

    public static boolean isShouldHideInput(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] leftTop = {0, 0};
            v.getLocationInWindow(leftTop);
            int left = leftTop[0], top = leftTop[1], bottom = top + v.getHeight(), right = left
                    + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 保留点击EditText的事件
                return false;
            } else {
                return true;
            }
        }
        return false;
    }

    public static Boolean hideInputMethod(Context context, View v) {
        InputMethodManager imm = (InputMethodManager) context
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            return imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
        }
        return false;
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        ViewManager.getInstance().finishActivity(this);
    }

    private Consumer mConsumer = new Consumer<RxEvent>() {
        @Override
        public void accept(RxEvent event) throws Exception {
            onCall(event);
        }
    };


    protected void onCall(RxEvent event) {

    }


    class MyCountDownTimer extends CountDownTimer {
        public MyCountDownTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {

            Log.d(TAG, "--------onTick-------millisUntilFinished:" + millisUntilFinished);
            int seconds = (int) millisUntilFinished / 1000;
            onCountDownTick(seconds);
        }

        @Override
        public void onFinish() {
            Log.d(TAG, "--------onFinish-------");
            onCountDownFinished();
        }
    }

    /**
     * 倒计时完成回调
     */

    protected void onCountDownFinished() {

    }

    protected void onCountDownTick(int seconds) {

    }

    protected abstract boolean isStartCountDown();
}
